# -*- coding: utf-8 -*-

from flask import Flask
from flask import request
from flask import Response
from flask import jsonify

import sys
reload(sys)
sys.setdefaultencoding('utf8')

import json
import build_data
import db


from flask_script import Manager, Server
from flask_script import Command


app = Flask(__name__)
app.debug = True
manager = Manager(app)


@app.route('/hello', methods=['GET'])
def hello():
  return 'hello'


@app.route('/nicolas', methods=['POST'])
def begin():
  dic = json.loads(request.get_data())
  action = dic['action']
  value = dic['value']
  func = build_data.Actions[action]['func']
  status = build_data.Actions[action]['status']
  func(value, status)
  return json.dumps({'status' : status}, ensure_ascii=False), 200


@app.route('/nicolas/<project_id>/<mr_id>/<git_commit>', methods=['GET'])
def get_build_data(project_id, mr_id, git_commit):
  row = build_data.BuildData.get_row(project_id, mr_id, git_commit)
  if row:
    return jsonify(row.to_json()), 200
  else:
    return json.dumps({'status' : -1}, ensure_ascii=False), 404


@app.route('/nicolas/<project_id>/builds/<limit>', methods=['GET'])
def get_build_data_limit(project_id, limit):
  return 404


# @manager.command
# def hello():
#   print('hello world')


if __name__ == '__main__':
  manager.add_command("run", Server())
  manager.run()
